from django.db import models

from mall import settings
from utils.models import BaseModel
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

# Create your models here.


class OAuthQQUser(BaseModel):
    """
    QQ登录用户数据
    """
    # users.User
    # 如果 只写User 它会在本子应用找User
    user = models.ForeignKey('users.User', on_delete=models.CASCADE, verbose_name='用户')
    openid = models.CharField(max_length=64, verbose_name='openid', db_index=True)

    class Meta:
        db_table = 'tb_oauth_qq'
        verbose_name = 'QQ登录用户数据'
        verbose_name_plural = verbose_name

    @staticmethod
    def generic_token_by_openid(openid):

        # 1.创建序列化器
        serializer = Serializer(settings.SECRET_KEY, 3600)
        # 2.对数据进行编码
        token = serializer.dumps({'openid': openid})
        # 3.token是butes类型
        return token.decode()

    @staticmethod
    def openid_by_token(token):
        # 1.创建序列化器
        serializer = Serializer(settings.SECRET_KEY, 3600)
        # 2.验证数据
        try:
            result = serializer.loads(token)
        except BadData:
            return None
        else:
            return result.get('openid')